<?php

// [ 订单 ]

namespace app\common\lib;
use think\Db;
use think\Session;
use app\common\lib\Code;

class Order
{
    // @param product_id   商品ID,项目主键
    //        pay_mark     支付标识,cp-初评付款,cx-诚信保证金
    //        openid       openid
    //        money        订单金额(分)
    //        body         商品描述
    //        trade_type   支付类型, JSAPI-公众号支付 NATIVE-扫码支付
    //        code         优惠码,可选
    //        out_trade_no 商户订单号
    public static function set($arr = [])
    {
        $member = Session::get('member');
        $data = [
            'member_id'   => $member['id'],
            'nickname'    => $member['info']['nickname'],
            'headimgurl'  => $member['info']['headimgurl'],
            'product_id'  => $arr['product_id'],
            'pay_mark'    => $arr['pay_mark'],
            'openid'      => $arr['openid'],
            'money'       => $arr['money'],
            'body'        => $arr['body'],
            'trade_type'  => $arr['trade_type'],
            'code'        => $arr['code'],
            'out_trade_no'=> $arr['out_trade_no'],
            'create_time' => time(),
            'finish_time' => 0,
        ];
        $num = Db::name('order')->insert($data);
        return ($num > 0);
    }

    // 回调处理
    public static function callbackHandle($out_trade_no)
    {
        $ret = Db::name('order')->where('out_trade_no',$out_trade_no)->where('finish_time',0)->find();
        if ( !is_null($ret) ) {
            switch ($ret['pay_mark']) {
                case 'cp':
                    $data['is_cp_pay'] = 1;
                    break;
                case 'cx':
                    $data['is_cx_pay'] = 1;
                    break;
            }
            $num = Db::name('project')->where('id',$ret['product_id'])->update($data);
            if ($num > 0) {
                // 改变优惠码状态
                empty($ret['code']) || Code::used($ret['code'],$ret['product_id']);
                // 改变订单状态
                $num = Db::name('order')->where('id',$ret['id'])->update(['finish_time'=>time()]);
                return ($num > 0);
            } else {
                return false;
            }
        } else {
            return true;
        }
    }
}